
<template>
  <div class="index-box" ref="index" >
    <div class="backBox">
        <span class="back" @click="back"><i class="el-icon-back"></i>返回</span>
    </div>
    <div class="shop-box" v-loading="loading">
      <div class="d-flex">
        <div class="left">
        <div class="title">商品信息</div>
        <div class="active-btn"  v-if="!pageDetail">
          <el-button type="primary" @click="hanleAdd" size="small" >{{setMsgForm.goodsId?'修改商品':'添加商品'}}</el-button>
        </div>
        <el-form  :model="form" size="small" ref="form" label-width="140px" class="form" v-if="setMsgForm.goodsId">
          <el-form-item label="商品编号" prop="goodsCategoryId">
           {{form.goodsCategoryName}}
          </el-form-item>
          <el-form-item label="商品分类" prop="goodsCategoryId">
           {{form.goodsCategoryName}}
          </el-form-item>
          <el-form-item label="商品名称" prop="columnNames">
           {{form.columnNames}}
          </el-form-item>
          <el-form-item label="商家门店名称" prop="goodsCode" >
            {{form.goodsCode}}
          </el-form-item>
          <el-form-item label="商家类型" prop="goodsName">
            {{form.goodsName}}
          </el-form-item>
          <el-form-item label="消费券抵扣" >
           {{form.couponPrice}}
          </el-form-item>
         <el-form-item label="参数" prop="rule">
           <div v-for="(item1,index1) in ruleList" class="rows">
                <el-input v-model="item1.name" class="input" placeholder="参数名称" disabled/>:
                <el-input v-model="item.val" class="input" v-for="(item,index) in item1.child" placeholder="参数值" disabled></el-input>
           </div>
         </el-form-item>
          <el-form-item label="参数规格" prop="ruleSet">
            <table border="1" cellspacing="0">
              <tr>
                <th v-for="item in ruleList">{{item.name}}</th>
                <th><span class="red">*</span>原价(元)</th>
                <th><span class="red">*</span>供货价(元)</th>
                <th><span class="red">*</span>平台售价(元)</th>
                <th><span class="red">*</span>库存(件)</th>
                <th>单位</th>
                <th>货号</th>
              </tr>
              <template v-for="item in dataList">
                  <tr>
                    <td v-for="(item1,index1) in ruleList">{{item['name'+index1]}}</td>
                    <td>
                      {{item.nameoriginal}}元
                    </td>
                    <td>
                      {{item.costPrice}}元
                    </td>
                    <td>
                      {{item.sellingPrice}}元
                    </td>
                    <td>
                      {{item.inventory}}
                    </td>
                    <td>
                      {{item.unit}}
                    </td>
                    <td>
                      {{item.code}}
                    </td>
                  </tr>
              </template>
            </table>
          </el-form-item>
        </el-form>
        </div>
        <div class="right">
          <div class="title">配置信息</div>
          <el-form :model="setMsgForm" label-position="right" :rules="rules" ref="setMsgForm">
            <el-form-item label="运营类型:" prop="operationConfigId" label-width="155px">
               <el-select v-model="setMsgForm.operationConfigId" placeholder="请选择">
                   <el-option  v-for="item in typeList" :key="item.typeKey" :label="item.name" :value="item.id"></el-option>
                 </el-select>
            </el-form-item>
            <el-form-item label="优惠金额:" prop="discountAmount" label-width="155px">
               <el-input v-model="setMsgForm.discountAmount" autocomplete="off" style="width: 217px;margin-right: 5px;"></el-input>元
            </el-form-item>
           <el-form-item label="配置图片:" prop="image" label-width="155px"  style="width:100%" >
             <MyUpImg :imagePreview='setMsgForm.image' size="340"  imageSize="rectangle" @change="imageChange($event, 'image')"></MyUpImg>
             <p style="color:#e4393c">图片规格为：宽 340px、高340px、大小不能超过2mb</p>
           </el-form-item>
            <el-form-item label="有效期类型:" prop="validTimeType" label-width="155px">
               <el-radio-group v-model="setMsgForm.validTimeType">
                 <el-radio :label="1">期间内有效</el-radio>
                 <el-radio :label="2">时间内有效</el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="固定时间内有效期:" prop="time" label-width="155px" v-if="setMsgForm.validTimeType=='1'">
               <el-date-picker
                 v-model="setMsgForm.time"
                 type="daterange"
                 placeholder="选择日期时间"
                 format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                 align="right"
                 :picker-options="pickerOptions">
               </el-date-picker>
            </el-form-item>
            <el-form-item label="时间区间有效期:" prop="hour" label-width="155px" v-if="setMsgForm.validTimeType=='2'">
              <el-date-picker
                    v-model="setMsgForm.date"
                    type="date"
                     format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker> -
                  <el-time-picker
                      is-range
                       format="HH:mm:ss" value-format="HH:mm:ss"
                      v-model="setMsgForm.hour"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围">
                    </el-time-picker>
              <!-- <el-date-picker
                    v-model="setMsgForm.time"
                    type="datetimerange"
                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker> -->
            </el-form-item>
            <el-form-item label="备注说明:" prop="remark" label-width="155px">
               <el-input v-model="setMsgForm.remark" autocomplete="off" type="textarea" rows="6"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="d-flex justify-center" v-if="!pageDetail">
        <el-button type="primary" @click="hanleSubmit('setMsgForm')"  :loading="btnLoading">确 定</el-button>
      </div>
    </div>

    <!--	选择商品	-->
    <el-dialog title="选择商品" :visible.sync="productsDialogVisible" :close-on-click-modal="false" v-dialogDrag>
      <div class="tableBox d-flex">
        <div class="leftBox" style="width: 160px;height:700px" >
            <el-tree :data="shopTypeList" node-key="categoryId" ref="tree"  current-node-key="" :props="defaultProps" default-expand-all :expand-on-click-node="false" @node-click="handleShopTypeNodeClick"></el-tree>
        </div>
        <div class="rightBox" style="flex:1">
          <div class="search-box">
              <el-form :inline="true" :model="shopDialog" size="small" ref="shopDialog" @submit.native.prevent
                class="demo-form-inline d-flex " id="searchBox"  style="flex-wrap: wrap;">
                <el-form-item prop="goodsCode" style="width:200px">
                    <el-input v-model="shopDialog.goodsCode" clearable placeholder="商品编号"></el-input>
                </el-form-item>
                <el-form-item prop="name" style="width:200px">
                    <el-input v-model="shopDialog.goodsName" clearable placeholder="商品名称"></el-input>
                </el-form-item>
                <el-form-item prop="storeName" style="width:200px">
                    <el-input v-model="shopDialog.storeName" clearable placeholder="商家名称"></el-input>
                </el-form-item>
                <el-form-item class="clearfix">
                  <el-button type="primary" @click="handleShopSearch()" icon="el-icon-search">搜索</el-button>
                </el-form-item>
              </el-form>
            </div>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in shopDialogList" :key="index">
            	<el-card :body-style="{ padding: '0px' }"  style="margin-bottom: 10px;">
            		<img :src="item.goodsImage" height="185" style="margin: auto;display: block;">
            		<div style="padding: 14px;">
            			<p style="margin: 0px;" class="ellipsis-item" :title="item.goodsName">{{item.goodsName}}</p>
                 <p style="margin: 0px;" class="ellipsis-item" :title="item.goodsCode">({{item.goodsCode}})</p>
            			<el-button size="small" @click="checkShop(item)" :disabled="btnLoading">选择</el-button>
            		</div>
            	</el-card>
            </el-col>
            <el-empty :image-size="200" v-if="!shopDialogList.length"></el-empty>

          </el-row>
          <MyPagination
             v-if="shopDialogList.length"
            :total="shopDialog.total"
            :page.sync="shopDialog.pageNum"
            :limit.sync="shopDialog.pageSize"
            @pagination="getShopList"
          />
        </div>
      </div>


    	<div slot="footer" class="dialog-footer">
    		<el-button size="small" @click="productsDialogVisible = false">取 消</el-button>
    	</div>
    </el-dialog>
    <!--	选择商品	-->

  </div>
</template>

<script>
  import { getConfigDetail,updateOperationConfig,addGoodsOperationConfig,getCategoryGoodsList,getGoodsDetail,goodsInfo,releaseGoods,goodsCategoryList,applyHotGoods, } from '@/api/getData';
  import common from "@/api/api";
  import option from '../../common/option.js';
  export default {
    name:'shopDetails',
    data() {
      return {
        loading: false,
        btnLoading:false,
        pageDetail:'',
        id:'',//组件id
        form:{

        },
        ruleList:[],
        dataList:[],
        typeList:[],//类型列表

        /*		表单数据		*/

        setMsgForm: {
          id:'',
          goodsId:'',
          storeId:'',
          categoryId:"",
        	operationConfigId: "",
          discountAmount:'',
          image:'',
          validTimeType:"",//有效期类型:1期间内有效2时间内有效
          time:[],
          validTimeStart:'',
          validTimeEnd:'',
          remark:'',
          date:'',
          hour:'',
        },
        /*		表单数据		*/
        rules: {
        	operationConfigId: [{required: true,message: '请选择运营类型',trigger: 'blur'}],
          discountAmount: [{required: true,message: '请填写优惠金额',trigger: 'blur'}],
          image: [{required: true,message: '请上传配置图片',trigger: 'blur'}],
          validTimeType: [{required: true,message: '请选择有效期类型',trigger: 'blur'}],
          time: [{required: true,message: '请选择有效期',trigger: 'blur'}],
          hour: [{required: true,message: '请选择有效期',trigger: 'blur'}],
        },

        shopDialog:{
          goodsCode:"",
          goodsName:'',
          categoryId: '',
          storeName:'',
          parentCategoryId:'',
          storeName:'',
          total:0,
          pageNum:1,
          pageSize:10,
        },
        defaultProps: {
           children: 'children',
           label: 'name'
        },
        shopDialogList:[],
        productsDialogVisible:false,
        shopTypeList:[]
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    created() {
      this.getCategoryDetails({categoryKey:'operation_config_type'}).then(res=>{
          this.typeList = res.data;
        })
      this.id =  this.$route.query.id;
      if(this.id){
        this.pageDetail = this.$route.query.type
        this.getShopOperationDetail();
        //this.editDataInfo(this.id)
      }
    },
    methods: {
      async getShopOperationDetail() {
        try {
          this.loading = true;
          const result = await getConfigDetail({id:this.id});
          if (result.code == 200) {
            this.editDataInfo(result.data.goodsId);

            this.setMsgForm.id = result.data.id;
            this.setMsgForm.goodsId = result.data.goodsId;
            this.setMsgForm.storeId = result.data.storeId;
            this.setMsgForm.categoryId = result.data.categoryId;
            this.setMsgForm.operationConfigId = result.data.operationConfigId;
            this.setMsgForm.discountAmount = result.data.discountAmount;
            this.setMsgForm.image = result.data.image;
            this.setMsgForm.validTimeType = result.data.validTimeType;
            if(result.data.validTimeType=='1'){
              this.setMsgForm.time = [result.data.validTimeStart.substring(0,10),result.data.validTimeEnd.substring(0,10)];
            }else if(result.data.validTimeType=='2'){
              //this.setMsgForm.time = [result.data.validTimeStart,result.data.validTimeEnd];
              this.setMsgForm.date = result.data.validTimeStart.substring(0,10);
              this.setMsgForm.hour = [result.data.validTimeStart.substring(11,19),result.data.validTimeEnd.substring(11,19)];
            }
             this.setMsgForm.remark = result.data.remark;

          } else {
            this.$message.error(result.msg);
          }
          //this.loading = false;
        } catch (err) {
         // this.loading = false;
          console.log(err)
        }
      },
      hanleSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            let data = JSON.parse(JSON.stringify(this.setMsgForm));
            if(data.validTimeType=='1'){
              data.validTimeStart = data.time[0]+' 00:00:00';
              data.validTimeEnd = data.time[1]+' 23:59:59';
            }else{
              data.validTimeStart = this.setMsgForm.date +' '+ this.setMsgForm.hour[0];
              data.validTimeEnd = this.setMsgForm.date +' '+ this.setMsgForm.hour[1];
            }
            if(this.id){
              updateOperationConfig(data).then((result) => {
               if (result.code == 200) {
                 this.$message.success(result.msg);
                 this.$router.go(-1);
               } else {
                 this.$message.error(result.msg);
               }
               this.btnLoading = false;
               });
            }else{
              addGoodsOperationConfig(data).then((result) => {
               if (result.code == 200) {
                 this.$message.success(result.msg);
                 this.$router.go(-1);
               } else {
                 this.$message.error(result.msg);
               }
               this.btnLoading = false;
              });
            }

          }
        })
      },
      editDataInfo(goodsId){
        this.loading = true;
        getGoodsDetail({goodsId:goodsId}).then((result) => {
          if (result.code == 200) {
              this.setMsgForm.categoryId =  result.data.goodsInfoDto.productCategoryId;

              let goodsInfoDto = result.data.goodsInfoDto;
              this.goodsType = goodsInfoDto.goodsType;
              this.tagList = result.data.tagList?result.data.tagList:[];
              this.form.couponPrice = goodsInfoDto.couponPrice;
              this.form.goodsCategoryId = goodsInfoDto.goodsCategoryId;
              this.form.goodsCode = goodsInfoDto.goodsCode;
              this.form.goodsCategoryName = goodsInfoDto.goodsCategoryName;
              this.form.goodsName = goodsInfoDto.goodsName;
              this.form.goodsImage = goodsInfoDto.goodsImage;
              this.form.columnNames = goodsInfoDto.columnNames;
              let imgDetails = [];
              let attachmentIds = [];
              for(let i=0;i<result.data.attachmentInfoList.length;i++){
                imgDetails.push(result.data.attachmentInfoList[i].fullFilename)
                attachmentIds.push(result.data.attachmentInfoList[i].attachmentId)
              }
              this.form.imgDetails = imgDetails;
              this.form.attachmentIds = attachmentIds;

              this.form.guarantee = goodsInfoDto.guarantee;
              this.form.provinceId = goodsInfoDto.provinceId;
              this.form.shipmentAddress = goodsInfoDto.shipmentAddress;
              if(goodsInfoDto.shipmentAddress=='1'){
                this.form.cityId = goodsInfoDto.cityId;
                this.form.areaId = goodsInfoDto.areaId;
                this.form.productAddress = goodsInfoDto.productAddress;
              }

              this.form.goodsDetails = JSON.parse(goodsInfoDto.goodsDetails);
              //this.form.addr = [(goodsInfoDto.provinceId).substring(0,6),(goodsInfoDto.cityId).substring(0,6),(goodsInfoDto.areaId).substring(0,6)];
              // parameterList:[{name:'',child:[{val:''}]}],
              // ruleList:[{name:'',child:[{val:'',key:''}]}],
              // dataList:[],//列表数据

              let ruleList = [];
              for(let i=0;i<result.data.specKeyList.length;i++){
                let obj = {name:result.data.specKeyList[i].specName,child:[]};
                for(let a=0;a<result.data.specKeyList[i].specValueList.length;a++){
                  obj.child.push({val:result.data.specKeyList[i].specValueList[a].specValueName})
                }
                ruleList.push(obj);
              }
              this.ruleList = ruleList;

              let parameterList = [];
              let parameterListUrl = JSON.parse(goodsInfoDto.paramsJson);
              for(let i =0;i<parameterListUrl.length;i++){
                parameterList.push({name:parameterListUrl[i].name,child:[{val:parameterListUrl[i].val}]})
              }
              this.parameterList = parameterList;

              let dataList = [];
              let skuStockList = result.data.skuStockList;
              for(let i =0;i<skuStockList.length;i++){
                dataList.push({
                  name0:skuStockList[i].specNameOne,
                  name1:skuStockList[i].specNameTwo,
                  name2:skuStockList[i].specNameThree,
                  nameoriginal:skuStockList[i].originalPrice,
                  costPrice:skuStockList[i].costPrice,
                  sellingPrice:skuStockList[i].salePrice,
                  inventory:skuStockList[i].stockNum,
                  code:skuStockList[i].cargoNo,
                  unit:skuStockList[i].unit})
              }
              this.dataList = dataList;



          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        });
      },
      async getTree() {
        try {
          const result = await goodsCategoryList();
          if (result.code == 200) {
            this.deptOptions = result.data
          } else {
            this.$message.error(result.msg);
          }
        } catch (err) {
          console.log(err)
        }
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.categoryName,
          children: node.children
        };
      },
      dataInfo(){/*表格计算*/
        let attrValue = [];// [['红', '黄', '蓝']['1', '3', '4']]
        for(let i=0;i<this.ruleList.length;i++){
          let arr = [];
          for(let a=0;a<this.ruleList[i].child.length;a++){
            arr.push(this.ruleList[i].child[a].val)
          }
          attrValue.push(arr)
        }
        let finalArr = this.cartesianProductOf(...attrValue);
        console.log(finalArr);

        let list = [];
        for(let i=0;i<finalArr.length;i++){
          let obj = {nameoriginal:'0',costPrice:'0',sellingPrice:'0',inventory:'0',code:'0',unit:''}
          for(let a=0;a<finalArr[i].length;a++){
            obj['name'+a] =finalArr[i][a];
          }
          list.push(obj)
        }
        this.dataList = list;
        console.log(list);

      },
      imageChange(path) {
        this.setMsgForm.image = path;
      },
      back(){
          this.$router.go(-1);//返回上一层
      },
      hanleAdd(){
        this.productsDialogVisible = true;
        this.getCategoryDetails({categoryKey:'product_category'})
        .then(res=>{
          this.shopTypeList = [{
            categoryId:'',
            children: res.data,
            name: "商品分类",
          }];
        })
        this.getShopList();
      },
      handleShopSearch(){
        this.shopDialog.pageNum = 1;
        this.getShopList();
      },
      async getShopList(){
        try {
          this.dialogLoading = true;
          let result = await getCategoryGoodsList(this.shopDialog);
          if (result.code == 200) {
            this.shopDialog.total = result.total;
            this.shopDialogList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.dialogLoading = false;
        } catch (err) {
          this.dialogLoading = false;
          console.log(err)
        }
      },
      /** 弹框商品类型树节点点击事件 **/
      handleShopTypeNodeClick(data){
        this.shopDialog.categoryId =  data.categoryId;
        this.shopDialog.parentCategoryId = data.parentId;
        this.getShopList();
      },
      checkShop(row){
        console.log(row)
        this.setMsgForm.goodsId = row.goodsId;
         this.setMsgForm.storeId = row.storeId;
        this.editDataInfo(row.goodsId);
        this.productsDialogVisible = false;
      },
    }
  }
</script>

<style scoped lang="scss">
  .activeBox{
    display:flex;
    justify-content:center;
  }
  .upGoodBox{
    height:100px;
    display:flex;
    align-items:center;
    justify-content: center;
    background: rgba(158, 187, 169, 0.15);
    color:#3A7654;
    margin-bottom:20px;
  }

  .el-checkbox-group{
    display: flex;
    flex-direction: column;
  }
  .jobNumber{
    text-align:center;
    color:#606266;
    margin:0;
  }
  .index-box /deep/ .el-checkbox{
    margin-bottom:15px;
  }
  .auditBox{
    padding: 20px 50px;
    background: rgba(158, 187, 169, 0.15);
    margin-bottom:20px;
    .steps{
      max-width:500px;
      margin:0 auto;
    }
  }
  .goodSet{
    padding: 50px 50px 30px 50px;
    background: rgba(158, 187, 169, 0.15);
    margin-bottom:20px;
    color:#606266;

  }
  .title{
    text-align: center;
    font-size:18px;
    margin-bottom:20px;
  }
  .el-icon-edit-outline{
    color: rgb(97, 153, 122);
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
  }
  .myQuillEditor{
    height:250px;
  }
  table {
    width: 100%;
  }

  th {
    height: 50px;
    text-align: left;
    border-bottom: 1px solid #EBEEF5!important;
    color:#909399;
    padding:0 5px;

  }
  table{
    border: 1px solid #EBEEF5;
  }
  td, th{
    border:none;
    white-space: nowrap;
    min-width: 80px;
  }
  td{padding:5px}
  .index-box{
    height:100%;
    overflow-y: auto;
  }
  .shop-box{
    margin: 0 auto;
    .left{
      width:50%;
      padding:0 10px;
    }
    .right{
      width:50%;
      padding:0 10px;
    }
  }
  .rows>div,.rows>button{
    margin-bottom: 5px;
  }
  .input{
    width:180px;
    margin-right:10px;
  }
  .form{
    padding:20px 0;
  }
  .boxs /deep/ .el-radio-group{
    	display: flex;
    	flex-wrap: wrap;
    }
    .boxs /deep/ .el-radio-group .el-radio{
    	width:100%;
    	margin-bottom: 10px;
    }
   .form /deep/ .avatar-uploader .el-upload-list__item{display: none;}
  .avatar-uploader{
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      height:100px;
      width:100px;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
        height: 30px;
        line-height: 30px;
        margin-top: 15px;
        margin-bottom: 10px;
        font-size: 28px;
        color: #8c939d;
    }
    .d-flex /deep/ .el-upload{
      display: block;
    }
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
    .text{
      margin: 0px;
      color: #8c939d;
    }
    .upImg /deep/ .el-upload--text{
      height:100%
    }
    .activeBox{
      display: flex;
      justify-content: center;
    }
    .el-upload-list--picture-card .el-upload-list__item{
        width:100px;
        height:100px;
    }
    .shop-box{
      margin: 0 auto;
      .left{
        width:50%;
        padding:0 10px;
      }
      .right{
        width:50%;
        padding:0 10px;
      }
    }
</style>
